package cn.kz.hrm.detail;

import cn.kz.hrm.domain.Userlogin;
import cn.kz.hrm.mapper.UserloginMapper;
import cn.kz.hrm.util.AjaxResult;
import feignclients.SystemFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class MyUserDetailService  implements UserDetailsService {

    @Autowired
    private UserloginMapper userloginMapper;

    @Autowired
    private SystemFeignClient systemFeignClient;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //1、根据用户名查询用户的数据
       Userlogin userlogin = userloginMapper.selectByUsername(name);
       if(userlogin==null){
           throw new RuntimeException("无效的用户！");
       }
       //先判断用户是前台用户登录还是后台用户登录，如果是后台用户登录才可以进行查询权限。
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (userlogin.getType() == Userlogin.SYSTEM_USER) {//后台用户是1

            AjaxResult ajaxResult = systemFeignClient.getPermissionById(userlogin.getId());
            if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
                throw new RuntimeException("查询权限出错！！！");
            }
            //查询的是权限的sn即只是描述。例如：department:save
            List<String> permissions = (List<String>)ajaxResult.getResultObj();
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
        }
        //将数据转换成对应的user对象
        User user = new User(name,userlogin.getPassword(),authorities);
        //调用feign接口进行查询用户拥有的权限
        return user;
    }
}
